//
//  TKYEdittingDataController.m
//  StationHouseHelper
//
//  Created by apple on 2018/6/20.
//  Copyright © 2018年 铁科院. All rights reserved.
//

#import "TKYEdittingDataController.h"
#import "TKYTabBarController.h"
#import "TKYEdittingDataCell.h"
#import "TKYUserModel.h"
@interface TKYEdittingDataController ()<UITableViewDelegate,UITableViewDataSource,UINavigationControllerDelegate,UIImagePickerControllerDelegate>
{
    BOOL _isSelectedCamera;// 是否选择相机
}
@property (nonatomic, strong)BaseTabelView *tabelView;
/**
 pickerController
 */
@property (nonatomic, strong)UIImagePickerController *pickerController;

//性别
@property (nonatomic, strong)NSString *sexStr;
//公司名称
@property (nonatomic, strong)NSString *companyNameStr;
//部门
@property (nonatomic, strong)NSString *departmentNameStr;

@property (nonatomic, strong)UIImage *headerImage;

@property (nonatomic, strong)TKYUserModel *userModel;
@end

@implementation TKYEdittingDataController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupUI];
    
    [self requestUserInfo];
    // Do any additional setup after loading the view from its nib.
}

//请求用户数据
- (void)requestUserInfo{
    NSString *url = [NSString stringWithFormat:@"%@%@token=%@&userId=%@",kApiBaseUrl,KGetUserInfoByUserIdURL,[[NSUserDefaults standardUserDefaults]objectForKey:kToken],[[NSUserDefaults standardUserDefaults]objectForKey:kUserID]];
    [KHttpRequestTool GET:url parameters:nil success:^(id response) {
        if ([response[@"code"] integerValue] == 0) {
            TKYUserModel *userModel = [TKYUserModel mj_objectWithKeyValues:response[@"user"]];
            
            self.userModel = userModel;
        }else{
            [SVProgressHUD showErrorWithStatus:response[@"msg"]];
        }
        [self.tabelView reloadData];
    } failure:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"网络错误"];
        
    }];
    
}


//设置界面
- (void)setupUI{
    self.navigationItem.title = @"编辑资料";
    self.navigationController.navigationBar.barTintColor = KNavColor;
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor whiteColor],NSFontAttributeName:[UIFont systemFontOfSize:19.0]}];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"back_btn"] style:UIBarButtonItemStylePlain target:self action:@selector(backBarButtonItemAction:)];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(saveAction:)];
    
    [self.view addSubview:self.tabelView];
}

- (void)saveAction:(UIBarButtonItem *)barButtonItem{
    NSLog(@"保存按钮");
    NSLog(@"%@%@", self.departmentNameStr,self.companyNameStr);
}

//返回按钮
- (void)backBarButtonItemAction:(UIBarButtonItem *)barButtonItem{
    
    UIViewController * presentingViewController = self.presentingViewController;
    do {
        if ([presentingViewController isKindOfClass:[TKYTabBarController class]]) {
            break;
        }
        presentingViewController = presentingViewController.presentingViewController;
        
    } while (presentingViewController.presentingViewController);
    
    [presentingViewController dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark--- UITableViewDelegate,UITableViewDataSource

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        return 80;
    }
    return 44;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 9;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    TKYEdittingDataCell *cell = [tableView dequeueReusableCellWithIdentifier:KEdittingDataCellID];
   
    switch (indexPath.row ) {
        case 0:{
            cell.titleLabel.text = @"头像";
            cell.contentLabel.hidden = YES;
            cell.contentTextField.hidden = YES;
            if (self.headerImage) {
                cell.headerImageV.image = self.headerImage;
            }else{
                cell.headerImageV.image = [UIImage imageNamed:@"member_selected"];
            }
            break;
        }
        case 1:{
            cell.titleLabel.text = @"姓名";
            cell.contentLabel.text = self.userModel.username;
            cell.contentLabel.hidden = NO;
            cell.contentTextField.hidden = YES;
            cell.headerImageV.hidden = YES;
            break;
        }case 2:{
            cell.titleLabel.text = @"性别";
            cell.contentLabel.hidden = YES;
            cell.contentTextField.hidden = NO;
            cell.contentTextField.text = self.userModel.sex;
            cell.headerImageV.hidden = YES;
            break;
        }case 3:{
            cell.titleLabel.text = @"工号";
            cell.contentLabel.hidden = NO;
            cell.contentLabel.text = @"23454wq";
            cell.contentTextField.hidden = YES;
            cell.headerImageV.hidden = YES;
            break;
        }case 4:{
            cell.titleLabel.text = @"手机";
            cell.contentLabel.hidden = NO;
            cell.contentLabel.text = self.userModel.mobile;
            cell.contentTextField.hidden = YES;
            cell.headerImageV.hidden = YES;
            break;
        }case 5:{
            cell.titleLabel.text = @"邮箱";
            cell.contentLabel.hidden = NO;
            cell.contentLabel.text = self.userModel.email;
            cell.contentTextField.hidden = YES;
            cell.headerImageV.hidden = YES;
            break;
        }case 6:{
            cell.titleLabel.text = @"公司";
            cell.contentLabel.hidden = YES;
            cell.contentTextField.hidden = NO;
            cell.contentTextField.text = @"北京经纬";
            cell.contentTextFieldBlock = ^(NSString *str) {
                
                self.companyNameStr = str;
            };
            cell.headerImageV.hidden = YES;
            break;
        }case 7:{
            cell.titleLabel.text = @"部门";
            cell.contentLabel.hidden = YES;
            cell.contentTextField.hidden = NO;
            cell.contentTextField.text = self.userModel.deptName;
            cell.contentTextFieldBlock = ^(NSString *str) {
            self.departmentNameStr = str;
                
            };
            
            cell.headerImageV.hidden = YES;
            break;
        }case 8:{
            cell.titleLabel.text = @"职务";
            cell.contentLabel.hidden = YES;
            cell.contentTextField.hidden = NO;
            cell.contentTextField.text = @"bim工程师";
            cell.headerImageV.hidden = YES;
            break;
        }
          
        default:
            break;
    }
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        [self selectedCameraOrAlbum];
    }
}

#pragma mark---UINavigationControllerDelegate,UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    if (_isSelectedCamera == YES) {
        UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
    }else{
        
    }
    UIImage *compreImage = [image scaleToWidth:1024];
    NSData * imageData = UIImageJPEGRepresentation(compreImage,0.3);
    NSString *imageBase64Str = [imageData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    TKYEdittingDataCell *edittingCell =(TKYEdittingDataCell *)[self.tabelView  cellForRowAtIndexPath:indexPath];
    edittingCell.headerImageV.image = image;
    [self.tabelView reloadData];

    self.headerImage = image;
    [picker dismissViewControllerAnimated:YES completion:nil];
}

//这个地方只做一个提示的功能
- (void)image:(UIImage*)image didFinishSavingWithError:(NSError*)error contextInfo:(void*)contextInfo
{
    if (error) {
        
    }
}

- (void)selectedCameraOrAlbum{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"请选择" message:@"" preferredStyle:UIAlertControllerStyleActionSheet];
    [alert addAction:[UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        _isSelectedCamera = NO;
        self.pickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentViewController:self.pickerController animated:YES completion:nil];
        
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        _isSelectedCamera = YES;
        self.pickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:self.pickerController animated:YES completion:nil];
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    
    [self presentViewController:alert animated:YES completion:nil];
}



#pragma mark-- 懒加载
- (BaseTabelView *)tabelView{
    if (_tabelView == nil) {
        _tabelView = [[BaseTabelView alloc]initWithFrame:CGRectMake(0, MyNavBarHeight, kScreenWidth, kScreenHeight) style:UITableViewStylePlain];
        _tabelView.delegate = self;
        _tabelView.dataSource = self;
        _tabelView.tableFooterView = [[UIView alloc]init];
        [_tabelView registerNib:[UINib nibWithNibName:@"TKYEdittingDataCell" bundle:nil] forCellReuseIdentifier:KEdittingDataCellID];
    }
    return _tabelView;
}

-(UIImagePickerController *)pickerController{
    if (!_pickerController) {
        UIImagePickerController *pickerController = [[UIImagePickerController alloc]init];
        pickerController.delegate = self;
        _pickerController=pickerController;
    }
    return _pickerController;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
